package com.pomr.service.simstorage.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pomr.dao.simstorage.SimStorageDao;
import com.pomr.model.equipmentstorage.EquipmentStorageDetail;
import com.pomr.model.simstorage.SimStorage;
import com.pomr.model.simstorage.SimStorageDetail;
import com.pomr.model.sys.User;
import com.pomr.service.simstorage.SimStorageService;
import com.pomr.util.page.Page;
@Service
public class SimStorageServiceImpl implements SimStorageService {
	@Autowired
	@Qualifier("simStorageDaoImpl")
	private SimStorageDao simStorageDao;

	@Override
	public Page<List<SimStorage>> searchStorages(String networkid, String agencyid, String manufacturerid, String page,
			String limit) throws Exception {
		StringBuilder sb = new StringBuilder();
		sb.append("from SimStorage ");
		int i=0;
		if(networkid!=null && !networkid.equals("")){
			i++;
			sb.append("where networkOperator.id = "+networkid+" ");
		}
		if(agencyid!=null && !agencyid.equals("")){
			
			if(i>0){
				sb.append("and ");
			}else{
				sb.append("where ");
			}
			sb.append("agency.id = "+agencyid+" ");
			i++;
		}
		if(manufacturerid!=null && !manufacturerid.equals("")){
			
			if(i>0){
				sb.append("and ");
			}else{
				sb.append("where ");
			}
			sb.append("manufacturer.id = "+manufacturerid+" ");
			i++;
		}
		
		
		String hqlStr = sb.toString();
		Page<List<SimStorage>> p = new Page<List<SimStorage>>();
		p.setCunrrentPage(Integer.valueOf(page));
		p.setPageSize(Integer.valueOf(limit));
		
		return simStorageDao.showPage(hqlStr, "select count(1) "+hqlStr, p);
	}

	@Override
	public Page<List<SimStorageDetail>> searchStorageDetails(String id, String page, String limit) throws Exception {
		if(id==null || id.equals("")){
			return null;
		}
		//查看库存--未被领用的设备以及报修的
		StringBuilder sb = new StringBuilder();
		sb.append("from SimStorageDetail detail where detail.simStorage.id = "+id);
		sb.append(" and (detail.equipmentStatus.id!=2 and detail.equipmentCon.id!=3)");
		sb.append(" and detail.id not in (select match.simdetail.id from Receive where receiveTime = null)");
		String hqlStr = sb.toString();
		List<SimStorageDetail> details = simStorageDao.findByHql(hqlStr);
		Page<List<SimStorageDetail>> p = new Page<List<SimStorageDetail>>();
		p.setCunrrentPage(Integer.valueOf(page));
		p.setPageSize(Integer.valueOf(limit));
		p.setRows(details);
		return simStorageDao.showPage(hqlStr, "select count(1) "+hqlStr, p);
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean deleteStorageDetails(String[] ids) throws Exception {
		int len = ids.length;
		SimStorageDetail detail = null;
		for(int i=0; i<len; i++){
			//先查询
			List<SimStorageDetail> ss = simStorageDao.findByHql("from SimStorageDetail where id = "+ids[i]+" and equipmentStatus.id != 2");
			if(ss==null || ss.size()<=0){//设备已被使用
				throw new Exception("设备正在被使用");
			}
			detail = ss.get(0);
			if(!simStorageDao.remove("delete from sim_storage_detail where id = "+ids[i])){
				throw new Exception("删除失败");
			}
		}
		//删除成功 更新库存
//		String hql = "update SimStorage set stockNumber = stockNumber-"+len+" where networkOperator.id="+detail.getNetworkOperator().getId()+
//				" and manufacturer.id="+detail.getManufacturer().getId()+" and agency.id="+detail.getAgency().getId();
//		if(!simStorageDao.editHql(hql)){
//			throw new Exception("更新库存失败");
//		}
		return true;
	}

	@Override
	public boolean editMoney(SimStorage storage) throws Exception {
		String hql = "update SimStorage set earnestmoney = "+storage.getEarnestmoney()+" where id = "+storage.getId();
		return simStorageDao.editHql(hql);
	}

	@Override
	public boolean damageStorageDetails(String[] ids) throws Exception {
		int len = ids.length;
		for(int i=0; i<len; i++){
			String hql = "update SimStorageDetail set equipmentCon.id=2 where id = "+ids[i]+"";
			if(!simStorageDao.editHql(hql)){
				throw new Exception("SIM卡报损失败");
			}
		}
		return true;
	}

	@Override
	public boolean repairStorageDetails(String[] ids) throws Exception {
		int len = ids.length;
		for(int i=0; i<len; i++){
			String hql = "update SimStorageDetail set equipmentCon.id=1 where id = "+ids[i]+"";
			if(!simStorageDao.editHql(hql)){
				throw new Exception("SIM卡修复失败");
			}
		}
		return true;
	}

	@Override
	public boolean cleanStorageDetails(String[] ids, String reason) throws Exception {
		int len = ids.length;
		for(int i=0; i<len; i++){
			String hql = "from SimStorageDetail where id="+ids[i]+" and equipmentStatus.id!=2 and equipmentStatus.id!=3";
			List<SimStorageDetail> details = simStorageDao.findByHql(hql);
			if(details!=null && details.size()>0){
				hql = "update SimStorageDetail set equipmentCon.id=3,reason='"+reason+"' where id = "+ids[i]+"";
				if(!simStorageDao.editHql(hql)){
					throw new Exception("SIM卡清库失败，id:"+ids[i]);
				}
			}else{
				throw new Exception("SIM卡已经绑定设备，id："+ids[i]);
			}
			
		}
		//减库存
		String hql = "update SimStorage set stockNumber = stockNumber-"+len+" where id=(select simStorage.id from SimStorageDetail where id="+ids[0]+")";
		if(!simStorageDao.editHql(hql)){
			throw new Exception("SIM卡清库失败,更新库存失败");
		}
		return true;
	}

	@Override
	public EquipmentStorageDetail searchBindEquipment(String id) throws Exception {
		String hql = "from EquipmentStorageDetail where id =( select d.equipmentdetail.id from DeviceMatch d where d.simdetail.id="+id+" and d.noBindTime=null)";
		List<EquipmentStorageDetail> details = simStorageDao.findByHql(hql);
		if(details!=null && details.size()>0){
			return details.get(0);
		}
		return null;
	}

	@Override
	public List<EquipmentStorageDetail> searchEquipmentLd(String kindid, String manufacturerid, String spec, User user)
			throws Exception {
		String hql = "from EquipmentStorageDetail where equipmentStorage.equipment.kind.id="+kindid
				+" and equipmentStorage.manufacturer.id="+manufacturerid+
				" and equipmentStorage.equipment.specification='"+spec+"'"
				+" and equipmentStorage.agency.id="+user.getAgency().getId()
				+ " and (equipmentCon.id!=3 and equipmentCon.id!=2)"//设备不能是清库或者损坏的
				+" and (equipmentStatus.id!=3 and equipmentStatus.id!=2)";//设备不能是已经绑定或者领用的
		
		return simStorageDao.findByHql(hql);
	}

	@Override
	public Page<List<SimStorageDetail>> searchSimBySnOfNoUse(String page, String limit, String sn, User user)
			throws Exception {
		String hql = "from SimStorageDetail where (equipmentCon.id!=3 and equipmentCon.id!=2) and (equipmentStatus.id!=3 and equipmentStatus.id!=2) "
				+ "and simStorage.agency.id=(select agency.id from User where id="+user.getId()+") "
				+ "and sn like '%"+sn+"%' ";
		Page<List<SimStorageDetail>> p = new Page<List<SimStorageDetail>>();
		p.setCunrrentPage(Integer.valueOf(page==null?"1":page));
		p.setPageSize(Integer.valueOf(limit));
		return simStorageDao.showPage(hql, "select count(1) "+hql, p);
	}
	
	

}
